package stage1.operation.module4.chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;

public class ReceiveThreat implements Runnable {
    Socket socket;
    BufferedReader bReader;
    private ArrayList<Socket> socketList;

    public ReceiveThreat(Socket socket, ArrayList<Socket> socketList) {
        super();
        this.socket = socket;
        this.socketList = socketList;
        try {
            bReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true) {
            try {
                String strMsg = bReader.readLine();
                if (null!=strMsg){
                    System.out.println(strMsg);
                }


                for (Socket clientSock : socketList) {
                    PrintWriter pWriter = new PrintWriter(clientSock.getOutputStream());
                    if (null!=strMsg){
                        pWriter.println(strMsg);
                        pWriter.flush();
                    }
                }
            } catch (IOException e) {
                ChatServer.socketList.remove(socket);
            } catch (ConcurrentModificationException co) {
                System.out.println("还不知道怎么处理");
            }
        }
    }
}
